import { Card, Tag, Empty, Select, Space, Table, Button, Popconfirm, message } from 'antd';
import { useMemo, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getMyCourses, cancelCourse } from '../../api/teacher';
import { useNavigate } from 'react-router-dom';
import type { Course } from '../../types';

export default function TeacherHome() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { data: list = [], isLoading } = useQuery({ queryKey: ['teacher', 'courses'], queryFn: getMyCourses });

  const weekdayLabels = ['周一','周二','周三','周四','周五','周六','周日'];
  const weeks = Array.from({ length: 20 }, (_, i) => i + 1);

  const cancelCourseMutation = useMutation({
    mutationFn: cancelCourse,
    onSuccess: () => {
      message.success('课程已取消');
      queryClient.invalidateQueries({ queryKey: ['teacher', 'courses'] });
    },
    onError: () => {
      message.error('取消课程失败，请重试');
    },
  });

  // 判断课程是否开课（选课人数达到最大容量的80%）
  const isCourseOpen = (course: Course) => {
    if (course.capacity === 0) return false;
    return (course.enrolledCount / course.capacity) >= 0.8;
  };

  // 表格列定义
  const columns = [
    {
      title: '课程名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '选课人数/最大量',
      key: 'enrollment',
      width: 150,
      render: (_: any, record: Course) => (
        <span>{record.enrolledCount} / {record.capacity}</span>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: 120,
      render: (_: any, record: Course) => {
        const isOpen = isCourseOpen(record);
        return (
          <Tag color={isOpen ? 'green' : 'red'}>
            {isOpen ? '已开课' : '未开课'}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Course) => {
        const isOpen = isCourseOpen(record);
        if (isOpen) {
          return <span className="text-gray-400">已开课，不可取消</span>;
        }
        return (
          <Popconfirm
            title="确定要取消这门课程吗？"
            description="取消后，已选课的学生将无法继续学习该课程。"
            onConfirm={() => cancelCourseMutation.mutate(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger
              loading={cancelCourseMutation.isPending}
            >
              取消课程
            </Button>
          </Popconfirm>
        );
      },
    },
  ];

  // 将时间映射为节次索引
  function timeToPeriod(start: string): number {
    const [h, m] = start.split(':').map(Number);
    const minutes = h * 60 + m;
    if (minutes < 9 * 60) return 0; // 8:00 -> 1-2节
    if (minutes < 12 * 60) return 1; // 10:00 -> 3-4节
    if (minutes < 15 * 60) return 2; // 14:00 -> 5-6节
    if (minutes < 18 * 60) return 3; // 16:00 -> 7-8节
    return 4; // 19:00 -> 9-10节
  }

  return (
    <div className="space-y-4 p-4">
      <TimetableCard list={list} weekdayLabels={weekdayLabels} weeks={weeks} timeToPeriod={timeToPeriod} navigate={navigate} isLoading={isLoading} />
      
      {/* 已审核通过的课程列表 */}
      <Card
        title="已审核通过的课程"
        className="shadow-md"
      >
        <Table
          dataSource={list}
          columns={columns}
          rowKey="id"
          loading={isLoading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 门课程`,
          }}
          locale={{
            emptyText: '暂无已审核通过的课程',
          }}
        />
      </Card>
    </div>
  );
}

function TimetableCard({ list, weekdayLabels, weeks, timeToPeriod, navigate, isLoading }: { list: any[]; weekdayLabels: string[]; weeks: number[]; timeToPeriod: (s:string)=>number; navigate: (path: string) => void; isLoading: boolean }) {
  const periods = ['1-2节', '3-4节', '5-6节', '7-8节', '9-10节'];
  // 定义每个时间段的默认时间范围
  const defaultTimeRanges = ['08:00-10:00', '10:00-12:00', '14:00-16:00', '16:00-18:00', '19:00-21:00'];
  const [selectedWeek, setSelectedWeek] = useState<number>(1);

  // 依据周次构建 cellMap（只放置包含该周的课）
  // 同时存储时间段信息以便在左侧显示时间
  const cellMap: Record<string, { course: any; active: boolean; timeSlot: any }[]> = useMemo(() => {
    const map: Record<string, { course: any; active: boolean; timeSlot: any }[]> = {};
    for (const c of list) {
      for (const s of c.timeSlots) {
        const inByArray = s.weeks ? s.weeks.includes(selectedWeek) : true;
        const inByRange = s.startWeek && s.endWeek ? (selectedWeek >= s.startWeek && selectedWeek <= s.endWeek) : true;
        const active = inByArray && inByRange;
        const p = timeToPeriod(s.start);
        const key = `${s.dayOfWeek}-${p}`;
        if (!map[key]) map[key] = [];
        map[key].push({ course: c, active, timeSlot: s });
      }
    }
    return map;
  }, [list, selectedWeek, timeToPeriod]);

  return (
    <Card
      loading={isLoading}
      title={
        <Space>
          <span>课表</span>
          <span className="text-slate-400 text-sm">（第</span>
          <Select value={selectedWeek} onChange={(v)=>setSelectedWeek(v)} options={weeks.map(w=>({value:w,label:String(w)}))} style={{ width: 96 }} />
          <span className="text-slate-400 text-sm">周）</span>
        </Space>
      }
    >
      {/* 表头 */}
      <div className="grid" style={{ gridTemplateColumns: '120px repeat(7, 1fr)' }}>
        <div className="text-slate-500 text-sm py-2 px-3">时间</div>
        {weekdayLabels.map((d, i) => (
          <div key={i} className="text-slate-500 text-sm py-2 px-3 text-center">{d}</div>
        ))}
      </div>
      {/* 网格 */}
      <div className="border rounded-md overflow-hidden">
        {periods.map((label, rowIdx) => {
          // 获取该行所有课程的时间（用于左侧显示）
          const timeRanges = new Set<string>();
          for (let day = 1; day <= 7; day++) {
            const key = `${day}-${rowIdx}`;
            const entries = cellMap[key] || [];
            entries.forEach(({ timeSlot }) => {
              timeRanges.add(`${timeSlot.start}-${timeSlot.end}`);
            });
          }
          const uniqueTimeRanges = Array.from(timeRanges);
          // 如果有课程时间则显示课程时间，否则显示默认时间
          const displayTime = uniqueTimeRanges.length > 0 ? uniqueTimeRanges.join(' / ') : defaultTimeRanges[rowIdx];
          
          return (
            <div key={rowIdx} className="grid border-b last:border-b-0" style={{ gridTemplateColumns: '120px repeat(7, 1fr)' }}>
              <div className="py-6 px-3 text-slate-600 border-r bg-slate-50">
                <div>{label}</div>
                <div className="text-xs mt-1 text-slate-500">
                  {displayTime}
                </div>
              </div>
              {Array.from({ length: 7 }, (_, colIdx) => {
                const day = colIdx + 1;
                const key = `${day}-${rowIdx}`;
                const entries = cellMap[key] || [];
                return (
                  <div key={colIdx} className="relative h-24 border-r last:border-r-0">
                    {entries.length === 0 ? null : entries.map(({ course, active, timeSlot }) => (
                      <div
                        key={course.id}
                        className={`absolute left-2 right-2 top-2 bottom-2 rounded-md border p-2 text-xs cursor-pointer transition-all hover:shadow-md ${active ? 'bg-blue-50 border-blue-300' : 'bg-slate-50 border-slate-200 opacity-50'}`}
                        onClick={() => {
                          navigate(`/teacher/course-students?id=${course.id}`);
                        }}
                      >
                        <div className="font-medium truncate">{course.name}</div>
                        <div className="mt-1 space-x-2">
                          <Tag color="blue">{formatWeekRange(course)}</Tag>
                          {timeSlot.room && (
                            <Tag color="green">{timeSlot.room}</Tag>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
      {list.length === 0 && <Empty className="mt-4" description="暂无课程" />}
    </Card>
  );
}

function formatWeekRange(course: any): string {
  let minStart: number | undefined;
  let maxEnd: number | undefined;
  for (const s of course.timeSlots || []) {
    if (s.weeks && s.weeks.length) {
      const wmin = Math.min(...s.weeks);
      const wmax = Math.max(...s.weeks);
      minStart = minStart === undefined ? wmin : Math.min(minStart, wmin);
      maxEnd = maxEnd === undefined ? wmax : Math.max(maxEnd, wmax);
    }
    if (s.startWeek !== undefined) {
      minStart = minStart === undefined ? s.startWeek : Math.min(minStart, s.startWeek);
    }
    if (s.endWeek !== undefined) {
      maxEnd = maxEnd === undefined ? s.endWeek : Math.max(maxEnd, s.endWeek);
    }
  }
  if (minStart !== undefined && maxEnd !== undefined) return `第${minStart}-${maxEnd}周`;
  return '周次待定';
}

